
import React from "react";
import { Checkbox, Pagination } from 'tinper-bee';
import Table from "bee-table";
import 'bee-table/build/Table.css';
import multiSelect from "bee-table/build/lib/multiSelect.js";
let MultiSelectTable = multiSelect(Table, Checkbox);
import createYGCPage from '../../../components/CreateYGCPage/index.jsx'
import YGCupload from '../../../components/YGCCreateUpload'
import {
    vendorsSetUrl,
    vendorsTrimStr,
    vendorsDanger,
    vendorsFmtDate,
    vendorsSuccess,
    vendorsGetUrlParam,
    vendorsGetStorage
} from 'utils/config.js';
import "./index.less";
import buttonClick from '../buttonEvent.js';
import { queryProject, queryList } from '../workStartReport.config.js'

let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
    tenantId = cookieStr.split('=')[1];
}

tenantId = tenantId || 'x61tnmfx';

const btnState = {
    ADD: 'add',
    EDIT: 'edit',
    BROWSE: 'browse'
}

const btnListTpl = {
    [btnState.BROWSE]: [
        {
            key: 'listadd',
            name: '新增',
            colors: "primary"
        },
        {
            key: 'listprint',
            name: '打印'
        },
        {
            key: 'listapproveDes',
            name: '审批详情'
        },
        {
            key: 'listattachment',
            name: '附件'
        },
        {
            key: 'refresh',
            name: '刷新'
        },
    ]
}

const Options = [
    { key: "7", value: "审批中" },
    { key: "9", value: "审批通过" },
    { key: "8", value: "已驳回" },
];

const searchTpl = {
    name: '查询模板',
    col: 4,
    dataSource: 'workstartreport_search_area',
    items: [
        {
            itemtype: "refer",
            refType: 'grid',
            refPk: 'pkProject',
            label: "项目名称",
            isMultiSelectedEnabled: true,
            required: false,
            selectShowKey: 'sname',
            reqRef: {
                queryCondition: function () {
                    // let org = this.search.getSearchValue({ refPk: 'pkSrc', requireKey: ['pkSrc', 'pkTenant'] });
                    return {
                        // pkOrg: org.length ? org[0] : null
                        pkTenant: tenantId,
                        projectState: '0,-1,',
                    }
                },
                setData: function (res) {
                    console.log(res);
                    return res.data.result.objects;
                },
                method: 'get',
                refUrl: "/projectInTeam/list",
                setCoByKey: [
                    { name: '项目编码', key: 'scode' },
                    { name: '项目名称', key: 'sname' },
                ],
            },
        },
        {
            itemtype: "refer",
            refType: 'tree',
            refPk: 'pkOrganization',
            label: "项目组织",
            isMultiSelectedEnabled: true,
            required: false,
            selectShowKey: 'sname',
            reqRef: {
                queryCondition: function () {

                    return { pkTenant: tenantId }
                },
                method: 'get',
                refUrl: "/organization/getPermOrgByUser",
            },
        },
        {
            itemtype: "refer",
            refType: 'grid',
            refPk: 'pkEnterprise',
            label: "施工单位",
            isMultiSelectedEnabled: false,
            required: false,
            selectShowKey: 'name',
            reqRef: {
                queryCondition: function () {
                    // let projectid = this.search.getSearchValue({ refPk: 'pkProject', requireKey: 'pkProject' });
                    return { role: 20 }
                },
                method: 'get',
                refUrl: "/ygcenterprise/queryEtpsByRole",
                setCoByKey: [
                    { name: '施工单位名称', key: 'name' },
                ],
            },
        },
        {
            itemtype: "refer",
            refType: 'grid',
            refPk: 'userId',
            label: "制单人",
            isMultiSelectedEnabled: true,
            required: false,
            selectShowKey: 'userName',
            reqRef: {
                queryCondition: function () {
                    let pkProject = this.search.getSearchValue({ refPk: 'pkProject', requireKey: 'pkProject' });
                    // return { pkProject: pkProject[0] }
                    return { pkProject: '' }
                },
                method: 'get',
                refUrl: "/billView/getUserRefList",
                setCoByKey: [
                    { name: '制单人', key: 'userName' }
                ]
            },
        },
        {
            itemtype: "section-date",
            refPk: 'sectionDate',
            label: "制单日期",
            isMultiSelectedEnabled: true,
            queryCondition: () => {
                return {}
            },
        },
        {
            itemtype: "select",
            refPk: 'billStatus',
            label: "单据状态",
            initialvalue: { value: 1, display: "自由态" },
            isMultiSelectedEnabled: true,
            isAjax: false,
            reqUrl: '',
            options: Options
        }
    ]
}

function setTableTpl() {
    let _self = this;
    const tableTpl = [
        {
            title: "序号", dataIndex: "index", key: "index", width: '3%',
            render(text, record, index) {
                return <span>{index + 1}</span>
            }
        },
        { title: "项目名称", dataIndex: "projectName", key: "projectName", width: '12%' },
        { title: "项目编码", dataIndex: "projectCode", key: "projectCode", width: '12%' },
        { title: "项目组织", dataIndex: "orgName", key: "orgName", width: '10%' },
        {
            title: "监理单位", dataIndex: "supervisionName", key: "supervisionName", width: '10%',
        },
        {
            title: "施工单位", dataIndex: "enterpriseName", key: "enterpriseName", width: '10%',
        },
        {
            title: "开工条件", dataIndex: "conditionName", key: "conditionName", width: '10%',
        },
        {
            title: "单据状态", dataIndex: "strBillstatus", key: "strBillstatus", width: '10%',
        },
        {
            title: "制单人", dataIndex: "creatorName", key: "creatorName", width: '7%',
        },
        {
            title: "操作", dataIndex: "operateAction", key: "operateAction", width: '7%',
            render(text, record, index) {
                return (
                    record.canApprove && (record.billstatus === 7 || record.billStatus === 5) ? <a className="ygc-stopwork-list-table-cell"
                        onClick={(e) => {
                            e.preventDefault();
                            _self.props.passreject.initPassRejectModal({ record, index, page: 'list', primaryKey: 'pkWorkstartreport' });
                        }}
                    >审批</a> : ''
                )
            }
        }
    ];
    return tableTpl
}

class WorkStartReportList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            paginationItems: 1, // 分页总数
            activePage: 1, // 当前页
            tableData: [], // 表格数据
            selectRows: [], // 选择行
        };
        this.srcHeight = 60;
        this.columns = setTableTpl.call(this);
        this.searchTpl = searchTpl;
    }
    componentDidMount() {
        console.log(this.state);
    }

    initTplAfter = () => {
        let kgbgproject = vendorsGetStorage('kgbgproject');
        let kgbgdaterange = vendorsGetStorage('kgbgdaterange');
        let workstartreportFromCardBrowse = window.sessionStorage.getItem('workstartreportFromCardBrowse');

        sessionStorage.removeItem('kgbgproject');
        sessionStorage.removeItem('kgbgdaterange');
        if (kgbgproject) {
            this.props.search.setSearchValByField('pkProject', kgbgproject.display, [{ pkProject: kgbgproject.value, sname: kgbgproject.display }]);
            this.props.search.setSearchValByField('sectionDate', kgbgdaterange);
            this.searchBtnClick.call(this, this.props.search.getSearchData().selectedS);
        }
        if (workstartreportFromCardBrowse === 'true') {
            let stateData = JSON.parse(window.sessionStorage.getItem('workstartreportListData'));
            window.sessionStorage.removeItem('workstartreportFromCardBrowse');
            window.sessionStorage.removeItem('workstartreportListData');
            this.setState(stateData);
        }
    }

    handlePassReject = (data) => {
        let { record, index } = data;
        let tableData = [...this.state.tableData];
        tableData[index] = record;
        this.setState({ tableData });
        this.props.passreject.closePassRejectModal();
    }

    // 存储选中行数据
    getSelectedDataFunc = (row) => {
        this.setState({ selectRows: row });
    }

    //分页搜索单据
    handleSelectPage = (e) => {
        let { selectedS } = this.props.search.getSearchData();
        this.setState({ activePage: e }, () => {
            let pageStart = 10 * (this.state.activePage - 1);
            selectedS.pageStart = pageStart;
            this.searchBtnClick.call(this, selectedS, { type: 'pagination' });
        });
    }

    render() {
        return (
            <div className="ygc-list ygc-kgbg-list">
                <div className=' header ygc-list-header-area'>
                    <div className='ygc-list-header-title'>开工报告</div>
                    <div className='ygc-list-header-button'>
                        {this.props.YGCreateButton({
                            btnTpl: btnListTpl,
                            buttonClick: buttonClick.bind(this)
                        })}
                    </div>
                </div>
                <div className="ygc-search-Area">
                    {this.props.YGCCreateSearch(this.searchTpl, { searchBtnClick: this.searchBtnClick })}
                </div>
                <div className="ygc-table-Area">
                    <div className="ygc-kgbg-table">
                        <MultiSelectTable
                            className='project_table'
                            columns={this.columns}
                            data={this.state.tableData}
                            showRowNum={true}
                            emptyText={() => '暂无数据'}
                            rowKey='pkWorkstartreport'
                            onRowDoubleClick={
                                (record, index, event) => {
                                    window.sessionStorage.setItem('workstartreportListData', JSON.stringify(this.state));
                                    this.props.router.push({ pathname: '/card', state: { cardState: 'browse', pk: record.pkWorkstartreport } });
                                }
                            }
                            scroll={{ y: 460 }}
                            bordered
                            getSelectedDataFunc={this.getSelectedDataFunc}
                        />
                        {this.state.tableData.length !== 0 &&
                            <Pagination style={{ float: 'right', margin: '15px 0' }}
                                first
                                last
                                prev
                                next
                                boundaryLinks
                                items={this.state.paginationItems}
                                maxButtons={5}
                                activePage={this.state.activePage} // 尝试解决某些特殊环境下没有值得情况
                                onSelect={this.handleSelectPage}
                            />
                        }
                    </div>
                </div>
                <YGCupload
                    ref={(upload) => { this.ygcUpload = upload }}
                    billType={'KGBG'}
                    pkBill={this.state.selectRows[0] && this.state.selectRows[0]['pkWorkstartreport']}
                    pkProject={this.state.selectRows[0] && this.state.selectRows[0]['pkProject']}
                />
                {this.props.YGCreatePassRejectModal({ handlePassReject: this.handlePassReject })}
                {this.props.YGCreateAproHistoryModal({})}
            </div>

        )
    }


    searchBtnClick = (searchInfo, selfInfo) => {
        console.log(searchInfo)
        let billStatus = [];
        if (searchInfo['billStatus'].length) {
            billStatus = searchInfo['billStatus'].map(cur => cur.key);
        }
        queryList(
            {
                "pkOrg": searchInfo['pkOrganization'].length ? searchInfo['pkOrganization'][0] : "",
                "billStatus": billStatus,
                "billType": "KGBG",
                "startTime": searchInfo['sectionDate'].startTime ? searchInfo['sectionDate'].startTime : "",
                "endTime": searchInfo['sectionDate'].endTime ? searchInfo['sectionDate'].endTime : "",
                "pkProject": searchInfo['pkProject'].length ? searchInfo['pkProject'] : [],
                "creators": searchInfo['userId'].length ? searchInfo['userId'] : [],
                "pageSize": 10,
                "pageStart": searchInfo['pageStart'] ? searchInfo['pageStart'] : 0,
                // "extendsParams":'',
                "extendsParams": {
                    pkorgs: searchInfo['pkOrganization'].join(','),
                    pkEnterprises: searchInfo['pkEnterprise'].join(','),
                }

                // "extendsParams":{"pkorgs":"pkorgs1,pkorgs2", "pkEnterprises": "pkEnterprises1,pkEnterprises2"}
                // "extendsParams":"{\"pkorgs\":\"pkorgs1,pkorgs2\", \"pkEnterprises\": \"pkEnterprises1,pkEnterprises2\"}"
            }, (res) => {
                let data = res.data;
                console.log(data);
                let type = selfInfo ? selfInfo.type : '';
                if (data.resultCode === 'ok') {
                    if (data.result && !type) {
                        vendorsSuccess({ 'text': `查询成功,共${data.result.count}条` })
                    } else if (type === 'refresh') {
                        this.setState({ activePage: 1 });
                        this.props.vendorsSuccess({ 'text': '刷新成功' });
                    } else if (type === 'pagination') {
                        // this.props.vendorsSuccess({ 'text': '查询成功' })
                    }


                    this.setState({
                        tableData: data.result == null ? [] : data.result.objects,
                        paginationItems: Math.ceil(data.result.count / 10)
                    })
                } else {
                    vendorsDanger({ 'text': data.exMsg })
                }
            }
        )
    }

    setRowKey = (record, index) => {
        return index
    };
}
export default createYGCPage({})(WorkStartReportList);
